package io.renren.modules.work.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.renren.common.utils.*;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.work.dao.ScProjectDao;
import io.renren.modules.work.entity.*;
import io.renren.modules.work.service.*;
import io.renren.vo.ScConsumablesVo;
import io.renren.vo.ScProjectEntityVo;
import io.renren.vo.ScProjectdtlVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;


@Service("scProjectService")
@Slf4j
public class ScProjectServiceImpl extends ServiceImpl<ScProjectDao, ScProjectEntity> implements ScProjectService {


    @Autowired
    private ScProjectdtlService scProjectdtlService;

    @Autowired
    private ScConsumablesService scConsumablesService;

    @Autowired
    private ScStockService scStockService;

    @Autowired
    private ScPurService scPurService;

    @Autowired
    private ScPurdtlService scPurdtlService;
    @Autowired
    private ScStocktranService scStocktranService;
    @Autowired


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //时间判断
        String sTime = null;
        String eTime = null;
        if(StringUtils.isNotBlank((String) params.get("sTime"))&&StringUtils.isNotBlank((String) params.get("eTime"))){
            sTime = sdf.format( Long.parseLong((String) params.get("sTime")));
            eTime = sdf.format( Long.parseLong((String) params.get("eTime")));
        }
        String[] shipSideNoList =null;
        if(StringUtils.isNotBlank((String) params.get("shipSideNoList"))){
            String shipSideNoListStr = (String) params.get("shipSideNoList");
            shipSideNoList = shipSideNoListStr.split(",");
        }



        IPage<ScProjectEntityVo> scProjectEntityVoIPage = baseMapper.selectProjectVolist(new Query<ScProjectEntityVo>().getPage(params),
                (String) params.get("projectno"),
                (String) params.get("projectname"),
                (String) params.get("projectStatus"),
                (String) params.get("companyname"),
                (String) params.get("cretimeSort"),
                sTime,
                eTime,
                shipSideNoList,
                (String) params.get("contractno"),
                (String) params.get("shipsideno"));
        return new PageUtils(scProjectEntityVoIPage);
    }

    @Override
    public ScProjectEntity saveProject(ScProjectEntity scProjectEntity) {
        //scProjectEntity.setProjectno(ConfigConstant.generateNo()); //工程编号自动生成
        baseMapper.insert(scProjectEntity);
        return scProjectEntity;
    }

    @Override
    @Transactional
    public R commitProject(String params, SysUserEntity user) {

        log.info("调用保存子工程接口");
        log.info("{}:",params);
        //工程id
        String dtlId = ConfigConstant.getId();

        ScProjectdtlVo scProjectdtlVo = JSONObject.parseObject(params, ScProjectdtlVo.class);
        //保存子工程
        ScProjectdtlEntity scProjectdtlEntity = new ScProjectdtlEntity();
        scProjectdtlEntity.setProjectdtlid(dtlId);
        scProjectdtlEntity.setProjectdtlno(ConfigConstant.generateNo());
        scProjectdtlEntity.setProjectdtlname(scProjectdtlVo.getProjectdtlname());
        scProjectdtlEntity.setHandleState(scProjectdtlVo.getHandleState());
        scProjectdtlEntity.setQualityState(scProjectdtlVo.getQualityState());
        scProjectdtlEntity.setWorkhours(scProjectdtlVo.getWorkhours());
        scProjectdtlEntity.setManhourfee(scProjectdtlVo.getManhourfee());
        scProjectdtlEntity.setMaterialcost(scProjectdtlVo.getMaterialcost());
        scProjectdtlEntity.setSpecialfee(scProjectdtlVo.getSpecialfee());
        scProjectdtlEntity.setOutsourcingFee(scProjectdtlVo.getOutsourcingFee());
        scProjectdtlEntity.setOthercost(scProjectdtlVo.getOthercost());
        scProjectdtlEntity.setMemo(scProjectdtlVo.getMemo());
        scProjectdtlEntity.setProjectid(scProjectdtlVo.getProjectid());
        scProjectdtlEntity.setCreman(user.getUsername());
        scProjectdtlEntity.setCremanid(Integer.parseInt(user.getUserId().toString()));
        scProjectdtlEntity.setBillno(scProjectdtlVo.getBillno());
        scProjectdtlService.save(scProjectdtlEntity);
        //保存器材
        for (ScConsumablesVo scConsumable : scProjectdtlVo.getScConsumables()) {
            ScConsumablesEntity scConsumablesEntity = new ScConsumablesEntity();
            scConsumablesEntity.setProjectdtlid(dtlId);
            scConsumablesEntity.setProjectid(scProjectdtlVo.getProjectid());
            scConsumablesEntity.setGoodsid(scConsumable.getGoodsid());
            scConsumablesEntity.setSingleprice(scConsumable.getSingleprice());
            scConsumablesEntity.setGoodsunit(scConsumable.getGoodsunit());
            scConsumablesEntity.setNum(scConsumable.getNum());
            scConsumablesEntity.setPrice(scConsumable.getPamount());
            scConsumablesEntity.setOutStatus(ConfigConstant.OUTSTATUS_INITIAL);
            scConsumablesService.save(scConsumablesEntity);
        }

        log.info("保存子工程完成");

        return R.ok();
    }

    @Override
    public R updateProject(String params) {
        log.info("调用更新工程接口");
        log.info("{}:",params);
        ScProjectEntityVo scProjectEntityVo = JSONObject.parseObject(params, ScProjectEntityVo.class);
        //更新主单
        QueryWrapper<ScProjectEntity> scProjectEntityQueryWrapper = new QueryWrapper<>();
        scProjectEntityQueryWrapper.eq("projectid",scProjectEntityVo.getProjectid());
        ScProjectEntity scProjectEntity =baseMapper.selectOne(scProjectEntityQueryWrapper);

        //判断是否处于同个月份，不一致的话泽无法修改数据
        Date cretime = scProjectEntity.getCretime();
        int month = cretime.getMonth();
        Date now = new Date();
        int nowMonth = now.getMonth();
        if(month!=nowMonth){
          //  return R.error("该单据是"+month+1+"月份的，无法再进行修改");
        }

        scProjectEntity.setMemo(scProjectEntityVo.getMemo());
        scProjectEntity.setProjectname(scProjectEntityVo.getProjectname());
        scProjectEntity.setHandleState(scProjectEntityVo.getHandleState());
        scProjectEntity.setCompanyid(scProjectEntityVo.getCompanyid());
        scProjectEntity.setCompanyname(scProjectEntityVo.getCompanyname());
        scProjectEntity.setContractid(scProjectEntityVo.getContractid());
        scProjectEntity.setContractno(scProjectEntityVo.getContractno());
        scProjectEntity.setOfferprice(scProjectEntityVo.getOfferprice());
        scProjectEntity.setReviewprice(scProjectEntityVo.getReviewprice());
        scProjectEntity.setRemainproject(scProjectEntityVo.getRemainproject());
        scProjectEntity.setStartTime(scProjectEntityVo.getStartTime());
        scProjectEntity.setEndTime(scProjectEntityVo.getEndTime());
        scProjectEntity.setShipsideno(scProjectEntityVo.getShipsideno());
        scProjectEntity.setEquipName(scProjectEntityVo.getEquipName());
        baseMapper.updateById(scProjectEntity);


        //更新细单
//        List<ScProjectdtlEntity> scprojectdtl = scProjectEntityVo.getProjectdtl();
//        for (ScProjectdtlEntity scProjectdtlEntity : scprojectdtl) {
//            scProjectdtlService.updateById(scProjectdtlEntity);
//        }
        log.info("更新工程完成");
        return R.ok();
    }

    /**
     * 验收确认
     * @param projectdtlids
     * @return
     */
    @Override
    @Transactional
    public R chkProject(String[] projectdtlids) {
        for (String projectdtlid : projectdtlids) {
            ScProjectdtlEntity scProjectdtlEntity = scProjectdtlService.getById(projectdtlid);

//            ScProjectEntity scProjectEntity = baseMapper.selectById(projectid);
//            if(!scProjectEntity.getProjectStatus().equals(ConfigConstant.PROJETCT_INITIAL)){
//                return R.error("只有初始状态的工程才能验收");
//            }
            //更新子工程单状态为验收确认状态
            scProjectdtlEntity.setProjectdtlStatus(ConfigConstant.PROJETCTDTL_FINISH);
            scProjectdtlService.updateById(scProjectdtlEntity);


            QueryWrapper<ScConsumablesEntity> scConsumablesEntityQueryWrapper = new QueryWrapper<>();
            scConsumablesEntityQueryWrapper.eq("projectdtlid", projectdtlid);
            List<ScConsumablesEntity> goodsList = scConsumablesService.list(scConsumablesEntityQueryWrapper);
            if(goodsList.size()>0){
                for (ScConsumablesEntity scConsumablesEntity : goodsList) {
                    scConsumablesEntity.setOutStatus(ConfigConstant.OUTSTATUS_FINISH);
                    scConsumablesService.updateById(scConsumablesEntity);
                    //生成出库记录
                    scStocktranService.generateStockTran(scConsumablesEntity.getConsumablesid());
                    //扣减库存，库存不够则生成采购单
                    scPurService.generatePur(scConsumablesEntity.getConsumablesid());
                }
            }



        }
        return R.ok();
    }

    @Override
    @Transactional
    public R finishProject(String[] projectids) {
        for (String projectid : projectids) {
            ScProjectEntity scProjectEntity = baseMapper.selectById(projectid);
            if(!scProjectEntity.getProjectStatus().equals(ConfigConstant.PROJETCT_CHKED)){
                throw new RuntimeException("存在状态不是验收的单据");
            }
            scProjectEntity.setProjectStatus(ConfigConstant.PROJETCT_FINISH);
            baseMapper.updateById(scProjectEntity);
        }
        return R.ok();
    }

    @Override
    public PageUtils queryPage2(Map<String, Object> params) {
        IPage<ScProjectEntity> page = this.page(
                new Query<ScProjectEntity>().getPage(params),
                new QueryWrapper<ScProjectEntity>()
        );
        return new PageUtils(page);
    }

    @Override
    public R getAllShipSideNo(String shipSideNo) {
        List<String> allShipSizeNo = baseMapper.getAllShipSizeNo();
        return R.ok().put("list",allShipSizeNo);
    }

    @Override
    public R outConfirm(String consumablesid) {
        ScConsumablesEntity scConsumables = scConsumablesService.getById(consumablesid);
        if(scConsumables.getOutStatus().equals(ConfigConstant.OUTSTATUS_FINISH)){
            return R.error("该器材已出库");
        }
        scConsumables.setOutStatus(ConfigConstant.OUTSTATUS_FINISH);
        scConsumablesService.updateById(scConsumables);

        //出库
        scStocktranService.generateStockTran(consumablesid);

        //扣减库存，库存不够则生成采购单
        scPurService.generatePur(consumablesid);

        return R.ok();
    }


}